package com.sky.d_fork_jion;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

/**
 * Fork/Join框架 在任务中抛出异常
 * http://ifeve.com/fork-join-5/
 * @Author:hjt
 */
public class ExceptionDemoTask extends RecursiveTask<Integer> {

	private static final long serialVersionUID = 1L;
	
	private int[] array;
	private int start, end;
	
	public ExceptionDemoTask(int[] array, int start, int end) {
		this.array = array;
		this.start = start;
		this.end = end;
	}

	@Override
	protected Integer compute() {
		System.out.printf("Task：start from %d to %d\n", start, end);
		if((end - start) < 10){
			//检查数组的索引号是3的位置，是这种情况抛出RuntimeException
			if((3 > start) && (end > 3)){
				throw new RuntimeException("This Task throws an Exception:Task from " + start + " to " + end);
			}
			
			try {
				//睡一秒
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			int mid = (end + start) / 2;
			ExceptionDemoTask t1 = new ExceptionDemoTask(array, start, mid);
			ExceptionDemoTask t2 = new ExceptionDemoTask(array, mid, end);
			invokeAll(t1, t2);
		}
		System.out.printf("Task end from %d to %d\n", start, end);
		return 0;
	}
	
	public static void main(String[] args) {
		int[] array = new int[100];
		ExceptionDemoTask task = new ExceptionDemoTask(array, 0, 100);
		
		ForkJoinPool pool = new ForkJoinPool();
		pool.execute(task);
		pool.shutdown();
		
		//使用awaitTermination()方法等待任务的结束。如果你想要等待任务的结束，
		//无论它花多长时间结束，将值1和TimeUnit.DAYS作为参数传给这个方法
		try {
			pool.awaitTermination(1, TimeUnit.DAYS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		if (task.isCompletedAbnormally()) {
			System.out.printf("Main: An exception has ocurred\n");
			System.out.printf("Main: %s\n",task.getException());
		}
		System.out.printf("Main: Result: %d",task.join());

			
	}

}

/**
 	
 
 */